﻿using System;
using System.Collections.Generic;
using System.ComponentModel.Composition.Hosting;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace Dubbo.Common.Extension
{
    public static class ExtensionLoader
    {
        private static CompositionContainer container;

        static ExtensionLoader()
        {
            Uri uri = new Uri(Assembly.GetExecutingAssembly().CodeBase);
            var binDir = Path.GetDirectoryName(uri.LocalPath);
            var catalog = new AggregateCatalog(new DirectoryCatalog(binDir));
            container = new CompositionContainer(catalog);
        }

        public static T GetExtension<T>(string name)
        {
            return container.GetExports<T, IExtensionMetadata>()
                .Where(e => e.Metadata.Name == name)
                .Select(e => e.Value)
                .FirstOrDefault();
        }
    }
}
